package domain.service.event;

import DateTools.DateUtil;
import core.util.ValidationUtil;
import domain.dao.base.UserInfoDao;
import domain.dao.event.EventImgInfoDao;
import domain.dao.event.EventMessageInfoDao;
import domain.dao.event.OperatorInfoDao;
import domain.dao.event.TunnelEventInfoDao;
import domain.entity.base.UserInfo;
import domain.entity.event.EventImgInfo;
import domain.entity.event.EventMessageInfo;
import domain.entity.event.EventOperatorInfo;
import domain.entity.event.TunnelEventInfo;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.ImageUploadUtil;
import util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by bowen on 2017-08-17.
 */
@Service
public class TunnelEventInfoService {

    private static final Logger logger = LoggerFactory.getLogger(TunnelEventInfoService.class);

    @Autowired
    private TunnelEventInfoDao eventInfoDao;
    @Autowired
    private OperatorInfoDao operatorInfoDao;
    @Autowired
    private EventImgInfoDao imgInfoDao;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private EventMessageInfoDao infoDao;

    /**
     * 上传事件
     *
     * @param entity
     * @return
     */
    public void create(TunnelEventInfo entity,String filePath) throws Exception {
//        Map<String, Double> lngLat = geocoder(entity.getAddress());
//        entity.setLat(lngLat.get("lat").toString());
//        entity.setLng(lngLat.get("lng").toString());
        entity.setEventId(entity.getPid());
        if (StringUtil.isNullOrEmpty(entity.getOperatorUsers())) {
            entity.setType(true);
        }
        //事件本身做已读记录
        EventMessageInfo messageInfo = new EventMessageInfo();
        messageInfo.setEventId(entity.getEventId());
        eventInfoDao.create(entity);
        if (entity.getPid() == 0) {
            eventInfoDao.updateEventById(entity.getId());
            messageInfo.setEventId(entity.getId());
        }
        messageInfo.setRevertId(entity.getId());
        messageInfo.setUserId(entity.getCreateUser());
        infoDao.create(messageInfo);
        if (!StringUtil.isNullOrEmpty(entity.getOperatorUsers())) {
            String operator[] = entity.getOperatorUsers().split(",");
            List<EventOperatorInfo> operatorInfos = new ArrayList<EventOperatorInfo>();
            for (int i = 0; i < operator.length; i++) {
                EventOperatorInfo info = new EventOperatorInfo();
                info.setEventId(messageInfo.getEventId());
                info.setRevertId(entity.getId());
                info.setUserId(operator[i]);
                operatorInfos.add(info);
            }
            operatorInfoDao.create(operatorInfos);
        }
        if (!StringUtil.isNullOrEmpty(entity.getImgs())) {
            String img[] = entity.getImgs().split(",");
            List<EventImgInfo> imgInfos = new ArrayList<EventImgInfo>();
            for (int i = 0; i < img.length; i++) {
                EventImgInfo info = new EventImgInfo();
                info.setEventId(entity.getId());
                info.setImg(img[i]);
                logger.info("++++++++++++++++++++++++++++++++++ImageUploadUtil.pressText++++++++++++++++++++++++++++++++++++++"+filePath+info.getImg());
                ImageUploadUtil.pressText(filePath+info.getImg(),entity.getAddress(),"jpg");
                imgInfos.add(info);
            }
            imgInfoDao.create(imgInfos);
        }
    }

    /**
     * 我发起的事件
     *
     * @param createUser 发起人
     * @return
     */
    public List<TunnelEventInfo> getMyCreateEvents(String createUser) {
        return eventInfoDao.getMyCreateEvents(createUser);
    }

    /**
     * '@'我的事件
     *
     * @param operatorUser 发起人
     * @return
     */
    public List<TunnelEventInfo> getAtEvents(String operatorUser) {
        return eventInfoDao.getAtEvents(operatorUser);
    }

    /**
     * 公共事件
     *
     * @param
     * @return
     */
    public List<TunnelEventInfo> getPublicEvents(String userId) {
        return eventInfoDao.getPublicEvents(userId);
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public TunnelEventInfo getEventById(long id) {
        return eventInfoDao.getEventById(id);
    }

    /**
     * 根据PID查询
     *
     * @param pid
     * @return
     */
    public TunnelEventInfo getEventByPid(long pid) {
        return eventInfoDao.getEventByPid(pid);
    }


    /**
     * 根据地址信息查询地址对应的经纬度
     *
     * @param address 地址
     * @return Map数据
     * @throws Exception
     */
    public static Map<String, Double> geocoder(String address) {
        Map<String, Double> resultMap = new HashMap<String, Double>();
        double lng = 0;
        double lat = 0;
        try {
            StringBuffer strBuffer = new StringBuffer("http://api.map.baidu.com/geocoder/v2/?");
            strBuffer.append("address=" + address);
            strBuffer.append("&output=json");
            strBuffer.append("&ak=" + ValidationUtil.baidu_ak);
            ClientRequest request = new ClientRequest(strBuffer.toString());
            ClientResponse<String> response = request.get();
            String strResult = "";
            if (response.getStatus() == 200) {
                strResult = response.getEntity(String.class);
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsN = objectMapper.readTree(strResult);
                lng = jsN.findValue("lng").getDoubleValue();
                lat = jsN.findValue("lat").getDoubleValue();
            }
            resultMap.put("lng", lng);
            resultMap.put("lat", lat);
            return resultMap;
        } catch (Exception e) {
            return null;
        }
    }

    public List<TunnelEventInfo> getAllEvents(String userId) {
        return eventInfoDao.getAllEvents(userId);
    }

    public int getTotalEvent(long eventId) {
        return eventInfoDao.getTotalEvent(eventId);
    }

    public List<TunnelEventInfo> getDetailByEventId(long eventId, String userId) {
        List<TunnelEventInfo> eventInfos = eventInfoDao.getDetailByEventId(eventId, userId);
        if (eventInfos != null && eventInfos.size() > 0) {
            for (TunnelEventInfo event : eventInfos) {
                event.setEventDate_txt(DateUtil.DateToString(event.getEventDate(),"yyyy-MM-dd HH:mm:ss"));
                List<EventImgInfo> imgInfos = imgInfoDao.getImgsByEventId(event.getId());
                if (imgInfos != null) {
                    event.setImgList(imgInfos);
                }
                UserInfo userInfo = userInfoDao.getUserInfoById(event.getEventUser());
                String user = "";
                List<Map<String, Object>> operatorList = operatorInfoDao.getOperatorByEventId(event.getEventId(),event.getId());
                for (Map<String, Object> operatorMap : operatorList) {
                    user += operatorMap.get("name") + ",";
                }
                if(user.equals("")){
                    event.setOperatorUsers(userInfo.getName());
                }else{
                    event.setOperatorUsers(userInfo.getName() + "@" + user.substring(0, user.length() - 1));
                }
                event.setEventUser(userInfo.getName());
            }
        }
        return eventInfos;
    }
}
